import 'dart:collection';
import 'dart:convert';
import 'dart:io';

import 'package:crypto/crypto.dart';
import 'package:dio/dio.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/datas/user_info.dart';
import 'package:flutter_syt/utils/utils_dlog.dart';
import 'package:intl/intl.dart';
import 'package:uuid/uuid.dart';

class RequestInterceptor extends Interceptor {
  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    _setRequestHeaders(options);
    handler.next(options);
  }

  @override
  Future onError(DioException err, ErrorInterceptorHandler handler) async {
    super.onError(err, handler);
    // logWrite("${err.requestOptions.uri.toString()}\n$err");
  }

  _setRequestHeaders(RequestOptions options) {
    // Platform
    var lang = Intl.getCurrentLocale();
    appContext.storage.setString('lang', lang);
    options.headers["mid"] = 1;
    options.headers["Authorization"] = UserInfo.me.token;
    DLog('UserInfo.me.token ${UserInfo.me.token}');
    options.headers["lang"] = lang;
    options.headers["OS"] = Platform.isIOS ? "ios" : "android";
    options.headers["VERSION"] = appContext.packageInfo.version;

    if (Platform.isIOS) {
      options.headers["DEVICE"] = appContext.iOSInfo.model;
      options.headers["DEVICE-VERSION"] = appContext.iOSInfo.systemVersion;
    } else {
      options.headers["DEVICE"] = appContext.andriodInfo.model;
      options.headers["DEVICE-VERSION"] =
          appContext.andriodInfo.version.release;
    }
    options.headers["DEVICE-NETWORK"] = appContext.connectionStatus.toString();
    options.headers["DEVICE-LOCATION"] = '';
    options.headers['timestamp'] =
        (DateTime
            .now()
            .millisecondsSinceEpoch ~/ 1000) - appContext.timeStamp;
    options.headers['nonce'] = const Uuid().v1();
    options.headers['source'] = 'app';

    options.headers['signature'] = headerToSignature(options);
    // DLog('signature   ${options.headers}');



    return options;
  }



  static String headerToSignature(RequestOptions options) {
    // Map map = options.headers;

    Map lowerMap = {};
    options.headers.keys.toList().forEach((element) {
      lowerMap[element.toString().toUpperCase()] = options.headers[element];
    });
    lowerMap.remove('CONTENT-TYPE');

    // if (options.data != null && options.data is Map) {
    //   lowerMap.addAll(options.data);
    // }
    // if (options.method == "GET") {
    //   Uri uri = Uri.parse(options.path);
    //   lowerMap.addAll(uri.queryParameters);
    // } else if (options.method == "PUT") {
    //   // DLog(options.headers);
    // }

    lowerMap.forEach((key, value) {
      lowerMap[key] =
          value.toString().replaceAll(' ', '').replaceAll('null', '');
    });

    SplayTreeMap splayTreeMap = SplayTreeMap.from(lowerMap);
    var json = jsonEncode(splayTreeMap);
    json = '$json&secretKey=d93a5def7511da3d0f2d171d9c344e91';
    Digest digest = md5.convert(utf8.encode(json));

    return digest.toString().toUpperCase();
  }

}
